package com.bsj.power.tool.testRtp;

import com.bsj.tools.Conv;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @Description TODO
 * @Date 2022/8/9 19:47
 **/
public class UdpClient {
    private String host;
    private int port;

    private EventLoopGroup group;
    private Bootstrap bootstrap;
    private Channel channel;

    UdpClient(String host, int port) {
        try {
            this.host = host;
            this.port = port;
            group = new NioEventLoopGroup();
            bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioDatagramChannel.class)
                    .remoteAddress(host, port)
                    .handler(new UdpDataHandler());
            channel = bootstrap.bind(0).sync().channel();
        }catch (Exception e){
            System.out.println(e);
        }
    }

    public void close(){
        group.shutdownGracefully();
    }

    public void send(byte[] data)throws Exception {
        try {
            ByteBuf byteBuf =  Unpooled.buffer(data.length);
            byteBuf.writeBytes(data);
            channel.writeAndFlush(
                    new DatagramPacket(
                            byteBuf,
                            new InetSocketAddress(
                                    host,port
                            )));
        }catch (Exception e){
            System.out.println(e);
        }
    }
    public static void main(String[] args) throws Exception {
        String host="127.0.0.1";
        int port = 20002;

        UdpClient udpDataSender = new UdpClient(host,port);
        List<byte[]> rtpStream = Rtp1.getRtpStream();
        for (byte[] data : rtpStream) {
            int seq = Conv.getShortNetOrder(data, 2);
            System.out.println("i:" + seq);
            Thread.sleep(2);
            udpDataSender.send(data);
        }
        Thread.sleep(10 * 1000);
        udpDataSender.close();
    }
}
